package com.msos.filter.PermisionFilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: PermisionFilter
 * @Description: TODO
 * @Author: hsx
 * @Date: 2022/4/6 15:52
 * @Version: v1.0
 */

@WebFilter(urlPatterns = "/*")
public class PermisionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获取请求路径
        String requestURI = req.getRequestURI();
        //包含login,easyui,h-ui的均无需拦截，直接放行
        if (requestURI.contains("login") || requestURI.contains("easyui") || requestURI.contains("h-ui")){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            //获取session中的对象信息
            Object loginCustomer = req.getSession().getAttribute("loginCustomer");
            Object loginManager = req.getSession().getAttribute("loginManager");
            //判断是否已登录
            if (loginCustomer == null && loginManager == null){
                resp.sendRedirect(req.getContextPath() + "/login");
            }else if(loginCustomer != null){
                filterChain.doFilter(servletRequest,servletResponse);
            }else if(loginManager != null){
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
